//
//  JKOAuthViewController.swift
//  新浪微博
//
//  Created by Jack.Lin on 16/7/3.
//  Copyright © 2016年 Jack.Lin. All rights reserved.
//

import UIKit
import SVProgressHUD

class JKOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        view = webView
        
        view.backgroundColor = UIColor.white()
        
        webView.scrollView.isScrollEnabled = false
        
        webView.delegate = self
   
        title = "登录新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))

    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(JKAppKey)&response_type=code&redirect_uri=\(JKRedirectURI)"
        
        // 加载授权界面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(JKAppKey)&redirect_uri=\(JKRedirectURI)"
        
        // 1> URL 确定要访问的资源
        guard let url = URL(string: urlString) else {
            return
        }
        
        // 2> 建立请求
        let request = URLRequest(url: url)
        
        // 3> 加载请求
        webView.loadRequest(request)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - 监听方法
    // 关闭控制器
    @objc private func close() {
        
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }


    // 自动填充
    @objc private func autoFill() {
       
        let js = "document.getElementById('userId').value = '646934313@qq.com'; " + "document.getElementById('passwd').value = 'linjie'; "
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScript(from: js)
        
    }

}

extension JKOAuthViewController: UIWebViewDelegate {

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 确认思路: 
        // 1. 如果请求地址包含 http://baidu.com 不加载页面 / 否则加载页面
        print("加载请求 --- \(request.url?.absoluteString)")
        if request.url?.absoluteString?.hasPrefix(JKRedirectURI) == false {
           
            return true
        }
        // 2. 从 http://baidu.com 回调地址的'查询字符串'中查找'code='
        if request.url?.query?.hasPrefix("code=") == false {
            print("取消授权")
            close()
            return false
        }
        
        // 3. 从 query 字符串中取出 授权码
        // 代码走到此处, url 中一定有 查询字符串, 并且包含 'code='
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("授权码 - \(code)")
        
        // 4. 使用授权码获取[换取] AccessToken
        JKNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
              
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
               
//                SVProgressHUD.showInfo(withStatus: "登录成功")
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: JKUserLoginSuccessedNotification), object: nil)
                
                self.close()
            }
          
        }
        
        return false
//        return true
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
